package com.qmt.qmttest;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

class Mp3Filter implements FilenameFilter {

	@Override
	public boolean accept(File dir, String filename) {
		// TODO Auto-generated method stub
		return (filename.endsWith(".mp4"));
	}	
}

public class AudioEngine extends ListActivity {
	
	/*lista*/
	private static final String SD_PATH = new String("/sdcard/QMTAudioRecorder/");
	private List<String> songs = new ArrayList<String>();
	private MediaPlayer mp = new MediaPlayer();
	/*endlista*/
	
	//private static final String AUDIO_RECORDER_FILE_EXT_3GP = ".3gp";
	private static final String AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4";
	private static final String AUDIO_RECORDER_FOLDER = "QMTAudioRecorder";

	private MediaRecorder recorder = null;
	private int currentFormat = 0;
	private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4,
			MediaRecorder.OutputFormat.THREE_GPP };
	//private String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP4, AUDIO_RECORDER_FILE_EXT_3GP };
	private String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP4};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.audiorecording);
		
		updatePlayList();

		Button stopPlay = (Button) findViewById(R.id.stopBtn);
        stopPlay.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mp.stop();
			}
		});
		setButtonHandlers();
		enableButtons(false);
		//setFormatButtonCaption();
	}
	
	@Override
	protected void onListItemClick(ListView list, View view, int position, long id) {
		// TODO Auto-generated method stub
		//super.onListItemClick(list, view, position, id);
		try{
			mp.reset();
			mp.setDataSource(SD_PATH + songs.get(position));			
			mp.prepare();
			mp.start();
		} catch(IOException e){
			Log.v(getString(R.string.app_name), e.getMessage());
		}
	}

	private void updatePlayList() {
		// TODO Auto-generated method stub
		songs.clear();
		File home = new File(SD_PATH);
		if( home.exists() ) {
			if(home.listFiles(new Mp3Filter()).length > 0){
				for(File file : home.listFiles(new Mp3Filter())){
					songs.add(file.getName());
				}
				
				ArrayAdapter<String> songList = new ArrayAdapter<String>(this, R.layout.song_item,songs);
				setListAdapter(songList);
			}
		}
	}
	
	private void deleteFiles() {
		// TODO Auto-generated method stub
		songs.clear();
		File home = new File(SD_PATH);
		if( home.exists() ) {
			if(home.listFiles(new Mp3Filter()).length > 0){
				for(File file : home.listFiles(new Mp3Filter())){
					//songs.add(file.getName());
					file.delete();
				}				
				ArrayAdapter<String> songList = new ArrayAdapter<String>(this, R.layout.song_item,songs);
				setListAdapter(songList);
			}
		}
	}

	private void setButtonHandlers() {
		((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick);
		((Button) findViewById(R.id.btnStop)).setOnClickListener(btnClick);
		((Button) findViewById(R.id.removeAllBtn)).setOnClickListener(btnClick);
		//((Button) findViewById(R.id.btnFormat)).setOnClickListener(btnClick);
	}

	private void enableButton(int id, boolean isEnable) {
		((Button) findViewById(id)).setEnabled(isEnable);
	}

	private void enableButtons(boolean isRecording) {
		enableButton(R.id.btnStart, !isRecording);
		//enableButton(R.id.btnFormat, !isRecording);
		enableButton(R.id.btnStop, isRecording);
	}

	
	/*
	private void setFormatButtonCaption() {
		((Button) findViewById(R.id.btnFormat))
				.setText(getString(R.string.audio_format) + " ("
						+ file_exts[currentFormat] + " buahaha )");
	}*/

	private String getFilename() {
		String filepath = Environment.getExternalStorageDirectory().getPath();
		File file = new File(filepath, AUDIO_RECORDER_FOLDER);

		if (!file.exists()) {
			file.mkdirs();
		}

		return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]);
	}

	private void startRecording() {
		recorder = new MediaRecorder();

		recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		recorder.setOutputFormat(output_formats[currentFormat]);
		recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		recorder.setOutputFile(getFilename());

		recorder.setOnErrorListener(errorListener);
		recorder.setOnInfoListener(infoListener);

		try {
			recorder.prepare();
			recorder.start();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void stopRecording() {
		if (null != recorder) {
			recorder.stop();
			recorder.reset();
			recorder.release();

			recorder = null;
		}
	}
	
	public static boolean deleteDirectory(File path) {
        // TODO Auto-generated method stub
        if( path.exists() ) {
            File[] files = path.listFiles();
            for(int i=0; i<files.length; i++) {
                if(files[i].isDirectory()) {
                    deleteDirectory(files[i]);
                }
                else {
                    files[i].delete();
                }
            }
        }
        return(path.delete());
    }

	private void displayFormatDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		//String formats[] = { "MPEG 4", "3GPP" };
		String formats[] = { "MPEG 4"};

		builder.setTitle(getString(R.string.choose_format_title))
				.setSingleChoiceItems(formats, currentFormat,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								currentFormat = which;
								//setFormatButtonCaption();

								dialog.dismiss();
							}
						}).show();
	}

	private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
		@Override
		public void onError(MediaRecorder mr, int what, int extra) {
			Toast.makeText(AudioEngine.this,
					"Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
		}
	};

	private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
		@Override
		public void onInfo(MediaRecorder mr, int what, int extra) {
			Toast.makeText(AudioEngine.this,
					"Warning: " + what + ", " + extra, Toast.LENGTH_SHORT)
					.show();
		}
	};

	private View.OnClickListener btnClick = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btnStart: {
				Toast.makeText(AudioEngine.this, "Start Recording",
						Toast.LENGTH_SHORT).show();

				enableButtons(true);
				startRecording();

				break;
			}
			case R.id.btnStop: {
				Toast.makeText(AudioEngine.this, "Stop Recording",
						Toast.LENGTH_SHORT).show();
				enableButtons(false);
				stopRecording();
				updatePlayList();

				break;
			}
			case R.id.removeAllBtn: {
				Toast.makeText(AudioEngine.this, "Removing All Files",
						Toast.LENGTH_SHORT).show();
				enableButtons(false);
				//File home = new File(SD_PATH);
				deleteFiles();
				//updatePlayList();

				break;
			}
			/*
			case R.id.btnFormat: {
				displayFormatDialog();

				break;
			}
			*/
			}
		}
	};
}